<script setup lang="ts">
//
import CustomNavbar from './componets/CustomNavbar.vue'
import CategoryPanel from './componets/CategoryPanel.vue'
import HotPanel from './componets/HotPanel.vue'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './componets/pageSkeleton.vue'

const isLoading = ref(false)

// 获取轮播图数据
const bannerItemList = ref<BannerItem[]>([])

// 获取分类数据
const categoryList = ref<CategoryItem[]>([])

// 获取热门推荐数据
const hotItemList = ref<HotItem[]>([])

const guessRef = ref<XtxGuessInstance>()

const getBannerList = async () => {
  const res = await getHomeBannerAPI()
  bannerItemList.value = res.result
}

const getHomeCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

const getHotItemList = async () => {
  const res = await getHomeHotAPI()
  hotItemList.value = res.result
}

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerList(), getHomeCategoryList(), getHotItemList()])
  isLoading.value = false
})

const onScrollToLower = () => {
  console.log('onScrollToLower')

  console.log(guessRef)

  guessRef.value?.getMore()
}
// 下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData() // 加载数据
  await Promise.all([getBannerList(), getHomeCategoryList(), getHotItemList()]) // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrollToLower"
    scroll-y="true"
    class="scroll-view"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-if="!isLoading">
      <XtxSwiper :list="bannerItemList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="hotItemList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
  height: 100%;
}
</style>
